from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel

# 定义登录请求模型
class LoginRequest(BaseModel):
    username: str
    password: str

# 定义令牌响应模型
class TokenResponse(BaseModel):
    access_token: str
    token_type: str

# 创建路由
router = APIRouter(prefix="/auth", tags=["认证"])

# 从配置文件中获取用户名和密码
from config import USERNAME, PASSWORD

# 简单的令牌存储（仅用于演示）
VALID_TOKENS = set()

# OAuth2密码流程
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token")

# 创建访问令牌
def create_access_token(username: str):
    # 简单的令牌生成（仅用于演示）
    token = f"demo-token-{username}-{len(VALID_TOKENS) + 1}"
    VALID_TOKENS.add(token)
    return token

# 验证令牌
def verify_token(token: str = Depends(oauth2_scheme)):
    if token not in VALID_TOKENS:
        raise HTTPException(status_code=401, detail="无效的认证凭证")
    # 从令牌中提取用户名（仅用于演示）
    if USERNAME in token:
        return USERNAME
    raise HTTPException(status_code=401, detail="无效的认证凭证")

# 登录接口
@router.post("/token", response_model=TokenResponse)
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    # print(f"form_data.username: {form_data.username}")
    # print(f"form_data.password: {form_data.password}")
    if form_data.username != USERNAME or form_data.password != PASSWORD:
        raise HTTPException(
            status_code=401,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token = create_access_token(form_data.username)
    return {"access_token": access_token, "token_type": "bearer"}

# 验证登录状态接口
@router.get("/verify")
def verify_login_status(username: str = Depends(verify_token)):
    return {"username": username, "authenticated": True}

# 登出接口
@router.post("/logout")
def logout(token: str = Depends(oauth2_scheme)):
    if token in VALID_TOKENS:
        VALID_TOKENS.remove(token)
    return {"message": "成功登出"}